package com.flute.framework.search;

import com.flute.framework.FluteMonitor;
import com.flute.framework.monitor.EventLogger;
import com.flute.framework.search.ISearcherProvider;
import com.flute.framework.search.SearcherInfo;
import com.flute.tools.timer.FlexTimer;

public class LuceneSearcherProvider implements ISearcherProvider {
	private SearcherInfo searcherInfo;
	private ProviderInfo providerInfo;
	private long updateInterval;

	public long getUpdateInterval() {
		return updateInterval;
	}

	public void setUpdateInterval(long updateInterval) {
		this.updateInterval = updateInterval;
	}

	public LuceneSearcherProvider() {

	}

	public void setSearcherInfo(SearcherInfo searcher) {
		this.searcherInfo = searcher;
	}

	@Override
	public SearcherInfo getSearcherInfo() {
		startTimer();

		while (searcherInfo == null) {
			info("搜索器'" + providerInfo.getLocation() + "'正在准备，等待1秒...");
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}

		return searcherInfo;
	}
	
	public SearcherInfo getCurrentSearcherInfo(){
		return searcherInfo;
	}

	private void startTimer() {
		String key = providerInfo.getLocation();
		if (!FlexTimer.getInstance().containsTask(key)) {
			FlexTimer.getInstance().startTimer(key,
					new LuceneSearcherUpdater(providerInfo, this), "update",
					updateInterval, true);
		}
	}

	public ProviderInfo getProviderInfo() {
		return providerInfo;
	}

	public void setProviderInfo(ProviderInfo providerInfo) {
		this.providerInfo = providerInfo;
	}

	private void info(String message) {
		if (EventLogger.containsEventKey(FluteMonitor
				.getSearcherProviderKey())) {
			EventLogger.info(message, FluteMonitor
					.getSearcherProviderKey());
		}
	}

}
